<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择菜品分类"
            style="width: 150px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="菜品名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['biz:product:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['biz:product:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="shopId"
          label="店铺ID"
          prop="shopName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="categoryId"
          label="菜品分类"
          prop="categoryName"
          min-width="150"
          align="center"
        />
        <el-table-column key="name" label="菜品名称" prop="name" min-width="150" align="center" />
        <el-table-column key="status" label="状态" prop="status" min-width="150" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? "显示" : "隐藏" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          key="description"
          label="菜品描述"
          prop="description"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="mainImage"
          label="主图"
          prop="mainImage"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="imageList"
          label="详情图"
          prop="imageList"
          min-width="150"
          align="center"
        />
        <el-table-column key="price" label="现价" prop="price" min-width="150" align="center" />
        <el-table-column
          key="originalPrice"
          label="原价"
          prop="originalPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="costPrice"
          label="成本价"
          prop="costPrice"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="stock"
          label="库存(-1表示无限)"
          prop="stock"
          min-width="150"
          align="center"
        />
        <el-table-column key="sales" label="销量" prop="sales" min-width="150" align="center" />
        <el-table-column key="tags" label="标签" prop="tags" min-width="150" align="center" />
        <el-table-column key="sort" label="排序权重" prop="sort" min-width="150" align="center" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['biz:product:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['biz:product:spec']"
              type="success"
              size="small"
              link
              @click="handleOpenSpecDialog(scope.row.id, scope.row.name)"
            >
              <template #icon><Setting /></template>
              规格配置
            </el-button>
            <el-button
              v-hasPerm="['biz:product:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 菜品表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="'40%'"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="店铺ID" prop="shopId">
          <el-input v-model="formData.shopId" placeholder="店铺ID" disabled />
        </el-form-item>

        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择菜品分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="formData.name" placeholder="菜品名称" />
        </el-form-item>

        <el-form-item label="菜品描述" prop="description">
          <el-input v-model="formData.description" placeholder="菜品描述" />
        </el-form-item>

        <el-form-item label="主图" prop="mainImage">
          <SingleImageUpload v-model="formData.mainImage" />
        </el-form-item>

        <el-form-item label="详情图" prop="imageList">
          <MultiImageUpload v-model="formData.imageList" :limit="4" />
        </el-form-item>

        <el-form-item label="现价" prop="price">
          <el-input-number v-model="formData.price" placeholder="现价" />
        </el-form-item>

        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="formData.originalPrice" placeholder="原价" />
        </el-form-item>

        <el-form-item label="成本价" prop="costPrice">
          <el-input-number v-model="formData.costPrice" placeholder="成本价" />
        </el-form-item>

        <el-form-item label="库存(-1表示无限)" prop="stock">
          <el-input-number v-model="formData.stock" placeholder="库存(-1表示无限)" />
        </el-form-item>

        <el-form-item label="销量" prop="sales">
          <el-input-number v-model="formData.sales" placeholder="销量" />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="如招牌，新品，热卖"
            style="width: 240px"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="排序权重" prop="sort">
          <el-input-number v-model="formData.sort" placeholder="排序权重" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">上架</el-radio>
            <el-radio :value="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 规格配置弹窗 -->
    <el-drawer
      v-model="specDialog.visible"
      :title="specDialog.title"
      :size="'40%'"
      @close="handleCloseSpecDialog"
    >
      <el-form ref="specFormRef" :model="specFormData" :rules="specRules" label-width="120px">
        <el-form-item label="菜品名称">
          <el-input v-model="specFormData.name" disabled />
        </el-form-item>

        <el-form-item label="口味做法配置" prop="specifications">
          <div class="specification-container">
            <div
              v-for="(spec, index) in specFormData.specifications"
              :key="index"
              class="specification-item"
            >
              <div class="specification-header">
                <el-form-item
                  :label="'规格' + (index + 1)"
                  label-width="-120px"
                  class="specification-title"
                >
                  <el-input
                    v-model="spec.name"
                    placeholder="请输入规格名称"
                    class="specification-input"
                  />
                </el-form-item>
                <el-button
                  type="danger"
                  class="delete-specification-btn"
                  @click="removeSpecification(index)"
                >
                  <el-tooltip class="box-item" effect="dark" content="删除规格" placement="top">
                    <el-icon><Delete /></el-icon>
                  </el-tooltip>
                </el-button>
              </div>

              <div class="specification-options-container">
                <div class="specification-title">规格选项</div>
                <div
                  v-for="(option, optionIndex) in spec.specOptions"
                  :key="optionIndex"
                  class="specification-option-input"
                >
                  <el-row>
                    <el-col :span="10">
                      <el-form-item label="选项名称" label-width="-120px">
                        <el-input v-model="option.name" placeholder="请输入规格选项值" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="价格调整">
                        <el-input-number
                          v-model="option.priceAdjustment"
                          placeholder="价格调整, 默认0元"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-button
                        v-if="spec.specOptions.length > 1"
                        type="danger"
                        class="delete-option-btn"
                        @click="removeSpecificationOption(index, optionIndex)"
                      >
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          content="删除规格选项"
                          placement="top"
                        >
                          <el-icon><Delete /></el-icon>
                        </el-tooltip>
                      </el-button>
                    </el-col>
                  </el-row>
                </div>

                <el-button
                  type="primary"
                  class="add-option-btn"
                  @click="addSpecificationOption(index)"
                >
                  添加选项
                </el-button>
              </div>
            </div>

            <el-button type="primary" class="add-specification-btn" @click="addSpecification()">
              添加规格
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitSpec()">保存</el-button>
          <el-button @click="handleCloseSpecDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Product",
  inheritAttrs: false,
});

import { defineAsyncComponent } from "vue";
import ProductAPI, {
  ProductPageVO,
  ProductForm,
  ProductPageQuery,
  ProductSpecConfigForm,
} from "@/api/biz/product";
import ProductCategoryAPI from "@/api/biz/product-category";
// 使用动态导入
const MultiImageUpload = defineAsyncComponent(
  () => import("@/components/Upload/MultiImageUpload.vue")
);
// 导入规格样式
import "@/styles/product.css";

const queryFormRef = ref();
const dataFormRef = ref();
const specFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ProductPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 菜品表格数据
const pageData = ref<ProductPageVO[]>([]);

// 菜品分类表格数据
const categoryOptions = ref<OptionType[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 规格配置弹窗
const specDialog = reactive({
  title: "",
  visible: false,
});

// 菜品表单数据
const formData = ref<ProductForm>({
  id: undefined,
  shopId: 1,
  categoryId: undefined,
  name: "",
  description: "",
  mainImage: "",
  imageList: [],
  price: undefined,
  originalPrice: undefined,
  costPrice: undefined,
  stock: undefined,
  sales: 0,
  tags: [],
  sort: 1,
  status: 0,
  specifications: [],
});

// 规格配置表单数据
const specFormData = ref<ProductSpecConfigForm>({
  id: undefined,
  name: "",
  specifications: [],
});

const tagOptions = ref<{ value: string; label: string }[]>([]);

// 菜品表单校验规则
const rules = reactive({
  shopId: [{ required: true, message: "请输入店铺ID", trigger: "blur" }],
  categoryId: [{ required: true, message: "请输入菜品分类", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
  mainImage: [{ required: true, message: "请上传主图", trigger: "blur" }],
  price: [{ required: true, message: "请输入现价", trigger: "blur" }],
});

// 规格配置表单校验规则
const specRules = reactive({
  specifications: [
    {
      required: true,
      message: "请至少添加一个规格",
      trigger: "blur",
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error("请至少添加一个规格"));
          return;
        }

        for (let i = 0; i < value.length; i++) {
          const spec = value[i];
          if (!spec.name || spec.name.trim() === "") {
            callback(new Error(`第${i + 1}个规格的名称不能为空`));
            return;
          }

          if (!spec.specOptions || spec.specOptions.length === 0) {
            callback(new Error(`第${i + 1}个规格的选项不能为空`));
            return;
          }

          for (let j = 0; j < spec.specOptions.length; j++) {
            const option = spec.specOptions[j];
            if (!option.name || option.name.trim() === "") {
              callback(new Error(`第${i + 1}个规格的第${j + 1}个选项不能为空`));
              return;
            }
          }
        }
        callback();
      },
      trigger: "blur",
    },
  ],
});

/** 查询菜品 */
function handleQuery() {
  loading.value = true;
  ProductAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询菜品分类 */
function handleCategoryQuery() {
  ProductCategoryAPI.getCategoryOptions().then((data) => {
    categoryOptions.value = data;
  });
}

/** 重置菜品查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开菜品弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改菜品";
    ProductAPI.getFormData(id).then((data) => {
      Object.assign(formData.value, {
        ...data,
        imageList: data.imageList || [], // 确保有默认值,
      });
      // 处理tags
      tagOptions.value =
        data.tags?.map((tag: string) => ({
          value: tag,
          label: tag,
        })) || [];
    });
  } else {
    dialog.title = "新增菜品";
  }
}

/** 提交菜品表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const submitData = { ...formData.value }; // 创建一个普通对象副本
      const id = submitData.id;
      if (id) {
        ProductAPI.update(id, submitData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProductAPI.add(submitData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭菜品弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.value.id = undefined;
}

/** 删除菜品 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ProductAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 打开规格配置弹窗 */
function handleOpenSpecDialog(id: number, name: string) {
  specDialog.visible = true;
  specDialog.title = "规格配置";
  specFormData.value.name = name;
  // 获取菜品规格数据
  if (id) {
    ProductAPI.getProductSpec(id).then((data) => {
      Object.assign(specFormData.value, data);
    });
  }
}

/** 关闭规格配置弹窗 */
function handleCloseSpecDialog() {
  specDialog.visible = false;
  specFormRef.value?.resetFields();
  specFormData.value = {
    id: undefined,
    specifications: [],
  };
}

/** 提交规格配置 */
function handleSubmitSpec() {
  if (!specFormData.value.id) {
    ElMessage.warning("菜品ID不能为空");
    return;
  }

  loading.value = true;
  ProductAPI.saveSpec(specFormData.value)
    .then(() => {
      ElMessage.success("规格配置保存成功");
      handleCloseSpecDialog();
      handleQuery(); // 刷新列表
    })
    .finally(() => (loading.value = false));
}

/** 添加规格 */
function addSpecification() {
  if (specDialog.visible) {
    // 规格配置弹窗
    specFormData.value.specifications = specFormData.value.specifications || [];
    specFormData.value.specifications?.push({
      name: "",
      specOptions: [
        {
          name: "",
          priceAdjustment: 0,
          sort: 1,
        },
      ],
    });
  } else {
    // 菜品表单弹窗
    formData.value.specifications = formData.value.specifications || [];
    formData.value.specifications?.push({
      name: "",
      specOptions: [
        {
          name: "",
          priceAdjustment: 0,
          sort: 1,
        },
      ],
    });
  }
}

/** 删除规格 */
function removeSpecification(index: number) {
  if (specDialog.visible) {
    // 规格配置弹窗
    specFormData.value.specifications = specFormData.value.specifications || [];
    specFormData.value.specifications?.splice(index, 1);
  } else {
    // 菜品表单弹窗
    formData.value.specifications = formData.value.specifications || [];
    formData.value.specifications?.splice(index, 1);
  }
}

/** 添加规格选项 */
function addSpecificationOption(specIndex: number) {
  if (specDialog.visible) {
    // 规格配置弹窗
    if (!specFormData.value.specifications || !specFormData.value.specifications[specIndex]) return;

    const spec = specFormData.value.specifications[specIndex];
    spec.specOptions = spec.specOptions || [];
    spec.specOptions.push({
      name: "",
      priceAdjustment: 0,
      sort: spec.specOptions.length + 1,
    });
  } else {
    // 菜品表单弹窗
    if (!formData.value.specifications || !formData.value.specifications[specIndex]) return;

    const spec = formData.value.specifications[specIndex];
    spec.specOptions = spec.specOptions || [];
    spec.specOptions.push({
      name: "",
      priceAdjustment: 0,
      sort: spec.specOptions.length + 1,
    });
  }
}

/** 删除规格选项 */
function removeSpecificationOption(specIndex: number, optionIndex: number) {
  if (specDialog.visible) {
    // 规格配置弹窗
    if (!specFormData.value.specifications || !specFormData.value.specifications[specIndex]) return;

    const spec = specFormData.value.specifications[specIndex];
    if (!spec.specOptions) return;

    spec.specOptions.splice(optionIndex, 1);

    // 重新排序
    spec.specOptions.forEach((option, idx) => {
      option.sort = idx + 1;
    });
  } else {
    // 菜品表单弹窗
    if (!formData.value.specifications || !formData.value.specifications[specIndex]) return;

    const spec = formData.value.specifications[specIndex];
    if (!spec.specOptions) return;

    spec.specOptions.splice(optionIndex, 1);

    // 重新排序
    spec.specOptions.forEach((option, idx) => {
      option.sort = idx + 1;
    });
  }
}

onMounted(() => {
  handleQuery();
  handleCategoryQuery();
});
</script>
